import React, {Component} from 'react'
import { Modal, Button, Input, Icon } from 'antd';
import message from '@wanhu/antd-legacy/lib/message'
import './customerApi'
import {agentHangUp,listen,callBtn,exportsendCallInfoFun,exportsendCallInfoFunInit,exportPatientId,exportPhone,exportIsMember,exportTaskType,importMemberThemeInit} from './customerApi'
import {start,stop,getTimeNow} from './commonJs/timer'
import connectModal from '../../../mixins/modal';
import { connectRouter } from '../../../mixins/router';
import './index.scss'
const { TextArea } = Input;
class Customer extends Component {
    state = {
        searchType: 'customer',
        showBox:false,
        callInfo:null,
        callTimer:"00:00:00",
        left:document.querySelector("body").offsetWidth/2-250,
        top:40,
        visible:false,
        themeVal:"",
        themeRemark:"",
        ifTheme:false,
        isMember:false,
        patientId:"",
    }
    constructor(props){
        super(props)
        this.elementWid = 500;
        this.elementHeight = 90;
        this.left = this.state.left || 0;
        this.top = this.state.top || 0;
        this.zIndex = 1;
        this.clientWidth = document.querySelector("body").offsetWidth;
        this.clientHeight = document.querySelector("body").offsetHeight;
        this._dragStart = this.dragStart.bind(this);
        // props传递配置项 end
    }
    async componentDidMount() {
        const self = this
        this.timer && clearTimeout(this.timer)
        // callOut()
        let getcallInfoLoad = localStorage.getItem("callInfo")
        if(getcallInfoLoad && getcallInfoLoad.indexOf("callInfos") != -1){
            let getCallInfo = JSON.parse(getcallInfoLoad);
            if(getCallInfo && (typeof getCallInfo=='object') && getCallInfo.callInfos){
                this.setState({
                    showBox:true,
                    callInfo:getCallInfo.callInfos,
                    isMember:await exportIsMember()
                })
                this.startTime()
            }
        }
        window.addEventListener("setItemEvent",async function (e) {
            // 电话条相关状态监听 start
            let getcallInfo = localStorage.getItem("callInfo")
            if(getcallInfo && (e.newValue.indexOf("callInfos") != -1) && (getcallInfo.indexOf("{") != -1)){
                let getCallInfo = JSON.parse(e.newValue);
                if(getCallInfo && (typeof getCallInfo=='object') && getCallInfo.callInfos && getCallInfo.callInfos.callType){
                    this.setState({
                        showBox:true,
                        callInfo:getCallInfo.callInfos,
                        isMember:await exportIsMember()
                    })
                    this.startTime()
                    if(getCallInfo.callInfos.ifTheme){
                        this.setState({
                            ifTheme:true,
                            themeVal:"",
                            themeRemark:"",
                        })
                    }else{
                        this.setState({
                            ifTheme:false
                        })
                    }
                    if(getCallInfo.callInfos.callType == "2"){
                        this.setState({
                            themeVal:"",
                            themeRemark:"",
                        })
                    }
                    if(getCallInfo.callInfos.themeCheck && getCallInfo.callInfos.themeCheck === true){
                        // this.callOff()
                    }
                }else{
                    this.setState({
                        showBox:false,
                    })
                }
                return
            }
            // 电话条相关状态监听 end
            // 电话条时间状态监听 start
            if((e.newValue.indexOf("callInfos") != -1) && (e.newValue.indexOf("callType") != -1)){
                let getCallInfo = JSON.parse(e.newValue);
                if(getCallInfo && (typeof getCallInfo=='object') && getCallInfo.callInfos){
                    this.setState({
                        showBox:true,
                        callInfo:getCallInfo.callInfos,
                        isMember:await exportIsMember()
                    })
                    this.startTime()
                }else{
                    this.setState({
                        showBox:false,
                    })
                }
            }
            // 电话条时间状态监听 end
            // 电话挂断监听（弹起备注弹框使用）
            if(e.newValue === "themeShowStr"){
                // this.callOff("themeShowStr")
            }
            // 通话结束，直接谈
            if(e.newValue === "popDiogTask"){
                this.setState({
                    themeVal:"",
                    themeRemark:"",
                    visible:true
                })
            }
        }.bind(this));
    }
    callOff(){ //外呼挂断
        stop()
        this.timer && clearTimeout(this.timer)
        this.setState({callTimer:"00:00:00"})
        agentHangUp()
    }
    callOn() {
        listen()
        stop()
        this.timer && clearTimeout(this.timer)
        this.setState({callTimer:"00:00:00"})
        this.startTime()
    }
    startTime(){
        this.timer && clearTimeout(this.timer)
        const time = start()
        this.timer = setInterval(
            () => {
              this.setState({callTimer:getTimeNow()})
        },1000);
    }
    handleSearch = value => {
        this.props.search(this.state.searchType, value);
        this.setState({
            keyword: value
        });
    }

    callTypeDom(){
        if(this.state.callInfo.callType == "2"){
            return (
                <div>
                    <div className="typeIconPos">
                        {/* <div className="typeIcon"><img src={call} /></div> */}
                        <div className="one">呼入中</div>
                        {/* <div className="two">{this.state.callTimer}</div> */}
                    </div>
                </div>
            )
        }
        if(this.state.callInfo.callType == "3"){
            return (
                <div>
                    <div className="typeIconPos">
                        <div className="two">{this.state.callTimer}</div>
                    </div>
                </div>
            )
        }
        return (
            <div>
                <div className="typeIconPos">
                    <div className="two">{this.state.callTimer}</div>
                </div>
            </div>
        )
    }
    callChoseDom(){
        if(this.state.callInfo.callType == "2"){
            return (
                <div>
                    <div className="left100 left100jt">
                        <div className="lb">
                            {/* <div onClick={()=>this.callOn()} className="iconGreen iconBox"><Icon type="phone" style={{ color: '#fff' }} /></div> */}
                            {/* <div onClick={()=>this.callOn()}>接听</div> */}
                        </div>
                        {/* <div className="rb">
                            <div onClick={()=>this.callOff()} className="iconRed iconBox"><Icon type="phone" style={{ color: '#fff' }} /></div>
                            <div onClick={()=>this.callOff()}>挂断</div>
                        </div> */}
                    </div>

                </div>
            )
        }
        return (
            <div className="left100">
                <div onClick={()=>this.callOff()} className={this.state.callInfo.callType==='1'?"iconGreen iconBox":"iconRed iconBox" }><Icon type="phone" style={{ color: '#fff' }} /></div>
                <div onClick={()=>this.callOff()}>挂断</div>
            </div>
        )
    }
    // 拖拽 start
    dragStart(ev) {
        ev.stopPropagation()
        let target = this.refs.dragElement;//ev.target;
        this.startX = ev.clientX;
        this.startY = ev.clientY;
        // 偏移位置 = 鼠标的初始值 - 元素的offset
        this.disX = this.startX - target.offsetLeft;
        this.disY = this.startY - target.offsetTop;
        this.zIndex += 1;
        this._dragMove = this.dragMove.bind(this);
        this._dragEnd = this.dragEnd.bind(this);
        let root=document.getElementById("app-body");
        root.style.cssText="background-color:#f8f8f8;user-select:none;"
        document.addEventListener('mousemove', this._dragMove, false);
        document.addEventListener('mouseup', this._dragEnd, false);
    }
    dragMove(ev) {
        this.clientX = ev.clientX;
        this.clientY = ev.clientY;
        // 元素位置 = 现在鼠标位置 - 元素的偏移值
        let left = this.clientX - this.disX;
        let top = this.clientY - this.disY;
        // 处理不可超出规定拖拽范围
        if (left < 0) {
          left = 0;
        }
        if (top < 0) {
          top = 0;
        }
        if (left > this.clientWidth - this.elementWid) {
          left = this.clientWidth - this.elementWid;
        }
        if (top > this.clientHeight - this.elementHeight) {
          top = this.clientHeight - this.elementHeight;
        }
        this.setState({
            left: left,
            top: top
        });
      }
      dragEnd(e) {
        const {onDragEnd} = this.props;
        document.removeEventListener('mousemove', this._dragMove);
        document.removeEventListener('mouseup', this._dragEnd);
        onDragEnd && onDragEnd({
          X: this.startX - this.clientX,
          Y: this.startY - this.clientY
        })
        let root=document.getElementById("app-body");
        root.style.cssText="background-color:#f8f8f8;"
      }
    // 拖拽 end
    // 备注弹窗 start
    callRemarks =()=>{
        this.setState({
          visible: true,
        });
    }
    hideModal = () => {
        this.setState({
            visible: false,
        });
    }
    submitModal =async () => {
        const self = this
        if(!this.state.themeVal){
            message.error("请输入主题")
            return
        }
        try{
            const getExportResult =await exportsendCallInfoFun(this.state.themeVal,this.state.themeRemark)
            if(getExportResult){
                self.setState({
                    visible:false
                })
                // importMemberThemeInit("","")
            }else{
                message.error("请求失败")
            }
        }catch(err){
            message.error(err)
        }
    }
    // 备注弹窗 end
    // 非任务界面先录入主题 start
    onChangeThemeVal = (e) => {
        this.setState({ themeVal: e.target.value });
    }
    onChangeThemeRemark = (e) => {
        this.setState({ themeRemark: e.target.value });
    }
    callBtnObj(){
        if(this.state.ifTheme && !this.state.themeVal){
            message.error("请输入通话主题");
            return
        }
        callBtn(this.state.themeVal)
    }
    themeClose(){
        this.setState({
            ifTheme:false,
            showBox:false,
        })
        this.callOff()
    }
    // 非任务界面先录入主题 end
    // 弹窗或者跳页面
    jumpLinknewMember(row) {
        const {router} = this.props
        const phone = exportPhone()
        // this.props.router.push(`/customerCenter?modal=addCustomer`)
        // this.router.openModal('addCustomer', phone);
        this.props.openModal('addCustomer', 'dht'+phone);
    }
    jumpLinkMember = () => {
        //to={`/customerDetails/${patient.id}/EssentialInfor?r=${encodeURIComponent(router.fullPath)}`}
        const patientId = exportPatientId()
        if(patientId){
            this.setState({
                patientId
            })
        }
        this.props.router.push(`/customerDetails/${patientId}/EssentialInfor`)
    }
    jumpLinkCreateTask(){
        const phone = exportPhone()
        this.props.router.push(`/newtask?phone=${phone}`)
    }
    render() {
        const self = this
        let styles = {}
        // 根据组件配置，为元素添加对应的样式
        styles['left'] = this.state.left;
        styles['top'] = this.state.top;
        styles['zIndex'] = this.zIndex;
        let isShow = this.state.visible
        let remarkShow = true
        // 如果是任务界面，不谈
        // const {router} = this.props
        // let match = router.match('/taskDetail/:taskId') || router.match('/taskPool/:taskPoolId/task/:taskId') || router.match('/newtask');
        // if (!exportTaskType()) {
        //     isShow = false
        //     remarkShow = false
        //     // exportsendCallInfoFunInit("","")
        // }
        // isShow = true
        let getPhone = ""
        if(this.state.callInfo && this.state.callInfo.phone){
            getPhone = this.state.callInfo.phone.substring(0,3)+"****"+this.state.callInfo.phone.substring(8,11);
        }
        let taskType = exportTaskType()
        return (
            <div>
                {this.state.showBox?<div
                className = "dragbox customerDom"
                onMouseDown = {this._dragStart}
                onMouseUp = {this._dragEnd}
                style={styles}
                ref="dragElement">
                    {this.state.ifTheme?<div className="themeBox">
                        <div className="themeClose"><Icon type="close-circle-o" onClick={()=>this.themeClose()} /></div>
                        <div className="themeInp">
                            <Input
                                placeholder="请输入通话主题"
                                prefix={<Icon type="edit" />}
                                value={this.state.themeVal}
                                onChange={this.onChangeThemeVal}
                            />
                        </div>
                        <div className="themeRem">
                            <Button type="primary" onClick={()=>{this.callBtnObj()}}>开始呼叫</Button>
                        </div>
                        <div className="clear"></div>
                    </div>:<ul>
                        <li className="borderR">
                            <div className="name">{this.state.callInfo.name} <span>{getPhone}</span> {this.state.callInfo.address}</div>
                            <div className="btn">
                                {this.state.isMember?<span onClick={this.jumpLinkMember.bind(this)}>会员详情</span>:<span onClick={this.jumpLinknewMember.bind(this)}>新建会员</span>}
                                {this.state.isMember?<span onClick={this.jumpLinkCreateTask.bind(this)}>创建任务</span>:null}
                                {remarkShow && !taskType?<span onClick={this.callRemarks}>通话备注</span>:null}
                            </div>
                        </li>
                        <li className="right">
                            <div className="phoneTypeIcon">
                                {this.callTypeDom()}
                            </div>
                            {this.callChoseDom()}
                        </li>
                    </ul>}
                </div>:null}
                <div>
                    <Modal
                        title="通话备注"
                        visible={isShow}
                        onOk={this.submitModal}
                        onCancel={this.hideModal}
                        okText="确认"
                        cancelText="取消"
                        maskClosable={false}
                        style={{top:"20%"}}
                    >
                        <div className="must">
                            <Input placeholder="请输入主题" value={this.state.themeVal} onChange={this.onChangeThemeVal} />
                        </div>
                        <div className="textarea">
                            <TextArea rows={4} value={this.state.themeRemark} placeholder="请输入通话备注" onChange={this.onChangeThemeRemark} />
                        </div>
                    </Modal>
                </div>
            </div>
        )
    }
}
// export default Customer;
export default connectRouter(connectModal(Customer));
